import { Button, Divider, Form, Input, message, Modal, Pagination, Select } from "antd";
import cm from "classnames";
import { useEffect, useState } from "react";
import AddressCard from "./components/AddressCard";
import styles from "./index.module.less";
import { addAddress, deleteAddress, getAddressAll, getAddressList, setDefaultAdd, updateAddress } from "@/services/address";
import { useForm } from "antd/es/form/Form";
import { useRequest } from "ahooks";
import { options } from "node_modules/axios/index.cjs";
import modal from "antd/es/modal";

const Address = () => {
  const [isModalOpen, setIsModalOpen] = useState({
    open: false,
    type: "add",
  });
  const [province, setProvince] = useState<any>([]);
  const [city, setCity] = useState<any>([]);
  const [regional, setRegional] = useState<any>([]);
  const [editData, setEditData] = useState<any>({});

  const [form] = useForm()

  const {data: userAddressList, run: getUserAddress} = useRequest(() => {
    return getAddressList().then((res) => {
        if (res.code === 200) {
          return res.data
        } else {
            message.error(res.message)
        }
    })
  })


  const getAddressCityList = ({type, parentCode, num}) => {
    getAddressAll({
        type,
        parentCode
    }).then((res) => {
        if (res.code === 200 ) {
            if (num === 0) {
                setProvince(res.data)
            } else if (num === 1) {
                setCity(res.data)
            } else if (num === 2) {
                setRegional(res.data)
            }
        }
    })
  }

  useEffect(() => {
    getAddressCityList({
        type: 'province',
        parentCode: '',
        num: 0,
    })
  }, [])

  const onDelete = (data) => {
    modal.confirm({
        title: "确定要删除该地址吗？",
        onOk() {
          deleteAddress({id: data.id}).then((res) => {
            if (res.code === 200) {
              message.success("删除成功");
              getUserAddress()
            }
          })
        },
      });
  }

  const onEdit = (data) => {
    setEditData(data)
    form.setFieldsValue({
        provinceName: data?.provinceName,
        provinceCode: data?.provinceCode,
        recipientName: data?.recipientName,
        recipientPhone: data?.recipientPhone,
        regionalCode: data?.regionalCode,
        regionalName: data?.regionalName,
        cityName: data?.cityName,
        cityCode: data?.cityCode,
        addressDetails: data?.addressDetails,
    })
    getAddressCityList({
        type: 'city',
        parentCode: data?.provinceCode,
        num: 1,
    })
    getAddressCityList({
        type: 'regional',
        parentCode: data?.cityCode,
        num: 2,
    })
    setIsModalOpen({ open: true, type: 'edit' })
  }

  const setDefault = (data) => {
    setDefaultAdd({addressId: data.id}).then((res) => {
        if (res.code === 200) {
          message.success("设置成功");
          getUserAddress()
        }
      })
  }
  
  const addAddressHandle = () => {
    if (isModalOpen.type === 'add') {
        form.validateFields().then((values) => {
            addAddress(values).then((res) => {
                if (res.code === 200) {
                    setIsModalOpen({ open: false, type: 'add' })
                    message.success('新增成功')
                    getUserAddress()
                    form.resetFields()
                } else {
                    message.error(res.message)
                }
            })
        })
    } else {
        form.validateFields().then((values) => {
            const params = {...editData, ...values}
            updateAddress(params).then((res) => {
                if (res.code === 200) {
                    setIsModalOpen({ open: false, type: 'add' })
                    message.success('修改成功')
                    getUserAddress()
                    form.resetFields()
                } else {
                    message.error(res.message)
                }
            })
        })
    }
  }
  return (
    <div className={cm(styles.CollectStyle)}>
      <Divider style={{ borderColor: "#7cb305" }} orientation="start">
        地址
      </Divider>
      <Button onClick={() => setIsModalOpen({ open: true, type: 'add' })} type="primary">新增收货地址</Button>
      <div className={cm(styles.list, "managerColumn")}>
        {userAddressList?.map((item) => {
          return (
            <div style={{ marginBottom: "15px" }}>
              <AddressCard
                data={item}
                onEdit={onEdit}
                onDelete={onDelete}
                setDefault={setDefault}
              />
            </div>
          );
        })}
      </div>
      <Modal 
        title={isModalOpen.type === 'add' ? '新增' : '编辑'} 
        open={isModalOpen.open} onCancel={() => setIsModalOpen({open: false, type: 'add'})} 
        onOk={addAddressHandle} 
        cancelText="取消" 
        okText="确定"
      >
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            autoComplete="off"
        >
            <Form.Item
                label="收货人"
                name="recipientName"
                rules={[{ required: true, message: '请输入收货人姓名!' }]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="手机"
                name="recipientPhone"
                rules={[{ required: true, message: '请输入收货手机!' }, {
                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                    message: '手机号格式有误！',
                  }, ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="省份"
                name="provinceCode"
                rules={[{ required: true, message: '请选择省份!' }]}
            >
                <Select fieldNames={{label: 'name', value: 'code'}} options={province} onChange={(value, option) => {
                    form.setFieldValue('provinceName', option?.name || '')
                    setRegional([])
                    form.setFieldsValue({
                        'cityCode': '',
                        'cityName': '',
                        'regionalCode': '',
                        'regionalName': ''
                    })
                    getAddressCityList({
                        type: 'city',
                        parentCode: value,
                        num: 1,
                    })
                }} />
            </Form.Item>
            <Form.Item
                label="城市"
                name="cityCode"
                rules={[{ required: true, message: '请选择城市!' }]}
            >
                <Select fieldNames={{label: 'name', value: 'code'}} options={city} onChange={(value, option) => {
                    form.setFieldValue('cityName', option?.name || '')
                    form.setFieldsValue({
                        'regionalCode': '',
                        'regionalName': ''
                    })
                    getAddressCityList({
                        type: 'regional',
                        parentCode: value,
                        num: 2,
                    })
                }} />
            </Form.Item>
            <Form.Item
                label="区县"
                name="regionalCode"
                rules={[{ required: true, message: '请选择区县!' }]}
            >
                <Select fieldNames={{label: 'name', value: 'code'}} options={regional} onChange={(value, option) => {
                    form.setFieldValue('regionalName', option?.name || '')
                }} />
            </Form.Item>
            <Form.Item
                label="详细地址"
                name="addressDetails"
                rules={[{ required: true, message: '请输入详细地址!' }]}
            >
                <Input.TextArea />
            </Form.Item>
            <Form.Item label="城市" name="provinceName" hidden></Form.Item>
            <Form.Item label="城市" name="cityName" hidden></Form.Item>
            <Form.Item label="城市" name="regionalName" hidden></Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Address;
